package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    private final StringRedisTemplate stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    public long nextId(String keyPrefix){//这个参数表示不同的业务。
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime time = LocalDateTime.of(2023, 1, 12, 5, 30, 30);
        long l = time.toEpochSecond(ZoneOffset.UTC);
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long prefix=nowSecond-l;//秒数的时间戳
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));//生成当前日期，如20201022
        long increment = stringRedisTemplate.opsForValue().increment("ice" + keyPrefix + date);
        return prefix << 32 |increment;//转化为2进制左移，低位补0

    }

}
